package com.beemans.common.utils

import androidx.lifecycle.LifecycleOwner
import com.beemans.common.data.constant.CommonStore
import com.beemans.common.ui.activities.CommonActivity
import com.tiamosu.navigation.page.FlyLifecycleObserver
import java.util.concurrent.TimeUnit

/**
 * @author tiamosu
 * @date 2021/3/22.
 */
object RefreshTaskHelper : FlyLifecycleObserver {
    private var refreshNativeAdService: CountDownService? = null
    private var refreshUserInfoService: CountDownService? = null

    /**
     * 信息流广告刷新
     * @param refreshTime 信息流刷新频率（间隔多久刷新一次，单位为秒）；注意：时间设置为0时相当于关闭
     */
    fun CommonActivity.refreshNativeAdTask(refreshTime: Int, callback: () -> Unit = {}) {
        lifecycle.addObserver(this@RefreshTaskHelper)
        if (refreshTime <= 0 || !CommonStore.isShowAd) return
        if (refreshNativeAdService == null) {
            refreshNativeAdService = CountDownService()
        }
        refreshNativeAdService?.startTask({
            callback.invoke()
        }, refreshTime.toLong(), refreshTime.toLong(), TimeUnit.SECONDS)
    }

    /**
     * 用户信息刷新
     * @param refreshTime 刷新时间，单位秒
     */
    fun CommonActivity.refreshUserInfoTask(
        refreshTime: Long = 3 * 60,
        refreshAction: () -> Unit = {}
    ) {
        lifecycle.addObserver(this@RefreshTaskHelper)
        if (refreshUserInfoService == null) {
            refreshUserInfoService = CountDownService()
        }
        refreshUserInfoService?.startTask({
            refreshAction.invoke()
        }, initialDelay = refreshTime, period = refreshTime, unit = TimeUnit.SECONDS)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        owner.lifecycle.removeObserver(this)
        refreshNativeAdService?.stopTask()
        refreshUserInfoService?.stopTask()
    }
}